package com.daniu.ssmdemo.service.impl;

import com.daniu.ssmdemo.mapper.AccountMapper;
import com.daniu.ssmdemo.mapper.TradeMapper;
import com.daniu.ssmdemo.pojo.Account;
import com.daniu.ssmdemo.pojo.Trade;
import com.daniu.ssmdemo.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional   //表示AccountServiceImpl类所有方法都必须进行事务处理
public class AccountServiceImpl implements AccountService {

    private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private TradeMapper tradeMapper;


    @Override
    public boolean transferAccount(
            String fromAccount,
            String toAccount,
            Double money) {
        boolean updateFlag = false;//标记变量  true表示转账失败，否则转账成功
        logger.info("-------------------------------开始转账---------------------------------");
        //1)、从转出账号减去交易金额，并且插入交易记录(支出)
        Account accountOut = accountMapper.getAccountByCardNo(fromAccount);
        Account accountIn = accountMapper.getAccountByCardNo(toAccount);
        if(accountOut == null){
            throw new InvalidAccountException("无效的转入账号，请重新输入！");
        }
        else {
            if (money <= accountOut.getBalance()) {
                if (accountIn != null) {
                    accountMapper.subAccountMoney(fromAccount, money);
                    Trade fromTrade = new Trade("支取", money, fromAccount);
                    tradeMapper.addTradeRecord(fromTrade);

//                    int x =  10;
//                    int y = 0;
//                    int z = x/y;
                    accountMapper.addAccountMoney(toAccount, money);
                    Trade toTrade = new Trade("存入", money, toAccount);
                    tradeMapper.addTradeRecord(toTrade);

                    updateFlag = true;
                } else {
                    throw new InvalidAccountException("无效的转入账号，请重新输入！");
                }
            } else {
                throw new NotMoneyEnoughException("转出账号余额不足，请充值后再转账！");
            }
        }
        //2)、转入账号增加交易金额，并且插入交易记录 (存入)

        logger.info("-------------------------------转账结束---------------------------------");


        return updateFlag;
    }
}
